var wxCharts = require('../../../utils/wxcharts.js');
const HOST = require('../../../config.js').host

var app = getApp();
var lineChart = null;
Page({
    data: {
      totalVisit:0,
      totalOrder:0,
      todayVisit: 0,
      totalMoney: 0,      
      totalReward:0,
      todayOrder: 0,
      todayMoney: 0,
      isfocus:false,
      isFirstBlur: true,
      isDisabled:true
      // todayReward:0
      // recentDayStatic:{},
      // recentDay:[]
    },
    touchHandler: function (e) {
        console.log(lineChart.getCurrentDataIndex(e));
        lineChart.showToolTip(e, {
            // background: '#7cb5ec'
        });
    },    
    createCanvas: function (categories, data, cId, chartTitle, unit, bit,colorIndex) {
      let self = this;
      var windowWidth = 320;
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth;
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }

      lineChart = new wxCharts({
        canvasId: cId,
        type: 'line',
        categories: categories,
        animation: true,
        background: '#f5f5f5',
        series: [{
          name: chartTitle,
          data: data,
          format: function (val, name) {
            return Number(val).toFixed(2) + unit;
          },
          colorIndex: colorIndex                              
        }, {
            name: chartTitle,
          data: [2, 0, 0, 3, null, 4, 0, 0, 2, 0],
          format: function (val, name) {
            return Number(val).toFixed(2) + unit;
          }
        }],
        xAxis: {
          disableGrid: true
        },
        yAxis: {
          title: chartTitle+"("+unit+")",
          format: function (val) {
            return Number(val) <0 ? 0 : Number(val).toFixed(0);
          },
          min: 0
        },
        width: windowWidth,
        height: 200,
        dataLabel: true,
        dataPointShape: true,
        extra: {
          lineStyle: 'line' //line 或者 curve
        }
      });
      self.updateData(categories, data, chartTitle, unit, bit);  
    },
    updateData: function (categories, data, chartTitle, unit, bit) {
        var series = [{
            name: chartTitle,
            data: data,
            format: function (val, name) {
              return Number(val).toFixed(bit) + unit;
            }
        }];
        lineChart.updateData({
            categories: categories,
            series: series
        });
    },
    cancel:()=>{
      wx.removeStorage({
        key: 'channelID',
      })
      wx.removeStorage({
        key: 'enterpriseID',
        success: function (res) {
          wx.reLaunch({
            url: '../../share/share',
          })
        }
      })
    }
    ,
    onLoad: function (e) {
      let self = this;
  //最近一周
      var myDate = new Date(); //获取今天日期
      myDate.setDate(myDate.getDate() - 6);
      var dateArray = [];
      var dateTemp;
      var flag = 1;
      for (var i = 0; i <= 6; i++) {
        dateTemp = (myDate.getMonth() + 1) + "-" + myDate.getDate();
        dateArray.push(dateTemp);
        myDate.setDate(myDate.getDate() + flag);
      }
      // 拉取数据
      let company = JSON.parse(e.statistics);
      wx.request({
        url: `${HOST}v1/qrcode/findByCompanyIdAndCompanyKey/${company.channelID}/${company.enterpriseID}`, //登陆请求
        method: 'GET',
        success: function (res) {
          if (res.data.sysCode === 1 && res.data.data) {
            let statistics = res.data.data;
            let dataArr = {
              "visits": [],
              "orders": [],
              "amounts": []
            }
            wx.request({
              url: `${HOST}v1/scanrecord/findAllRecords/${statistics.id}`, //请求七日数据
              method: "GET",
              success: function (res) {
                if (res.data.sysCode === 1) {
                  dataArr.visits = res.data.data.scan.reverse()
                  dataArr.orders = res.data.data.order.reverse()
                  dataArr.amounts = res.data.data.money.reverse();
                  //请求结束绘图
                  self.setData({
                    // recentDay: dateArray,        
                    totalVisit: statistics.scanNum,
                    totalOrder: statistics.orderNum,
                    totalMoney: statistics.totalPrice.toFixed(0),
                    // 
                    todayVisit: dataArr.visits[6],
                    todayOrder: dataArr.orders[6],
                    todayMoney: Number(dataArr.amounts[6]).toFixed(0),
                    userName: statistics.userName,
                    codeId: statistics.id
                    // recentDayStatic: statistics.recentDayStatic
                  })
                  let chartTitle = ["七日访问量", "七日下单人数", "七日下单金额"];
                  let chartUnit = ["人", "人", "元"];
                  let bit = [0, 0, 2]
                  let index = 0;
                  //最近七天：dateArray，最近七天数据：statistics.recentDayStatic ,方便起见每个canvas id 等于相应数据key值
                  for (let item in dataArr) {
                    self.createCanvas(dateArray, dataArr[item], item, chartTitle[index++], chartUnit[index - 1], bit[index - 1], (index + 1));
                  }
                  //提成百分比获取
                  wx.request({
                    url: `${HOST}v1/joininfo/findByCompanyId/${statistics.companyId}`,
                    method: "GET",
                    success: function (res) {
                      if (res.data.sysCode === 1) {
                        self.setData({
                          totalReward: (self.data.totalMoney * res.data.data.percentVal).toFixed(0),
                        })
                      }
                    }
                  })
                }
              }
            });
          }
        }
      })
    
    },
    editNickName:function(e) {
      this.setData({
        isDisabled: false,        
        isfocus:true
      })
    },
    submitUserName:function(e) {
      if (this.data.isFirstBlur) return(
        this.setData({
          isFirstBlur:false,
          isfocus: false       
        })
      );
      this.setData({
        isfocus: false,
        isDisabled: true
      })
      let self = this;
      if (!e.detail.value) return(
        wx.showModal({
          title: '提示',
          content: '用户名不能为空，请重新填写',
        })
      )
      wx.request({
        url: HOST + 'v1/qrcode/saveUserName',
        data:{
          "id": self.data.codeId,
          "userName": e.detail.value 
        },
        method: "POST",
        success:function(res) {
          
        }
      })
    },
    onShow:function() {
      this.setData({
        isfocus: false,
        isDisabled: true          
                
      })
      console.log("isfocus:"+this.data.isfocus);
    }
});